package utils

import (
	"crypto/md5"
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"fmt"
	goQrcode "github.com/skip2/go-qrcode"
	"image"
	_ "image/gif"
	_ "image/jpeg"
	_ "image/png"
	"io"
	"os"
)

func FileExists(filePath string) bool {
	if _, err := os.Stat(filePath); err != nil {
		return false
	} else {
		return true
	}
}

// SplitIntoChunks 指定截断长度,来截断字符串
func SplitIntoChunks(s string, chunkSize int) []string {
	var chunks []string
	runes := []rune(s)

	for i := 0; i < len(runes); i += chunkSize {
		end := i + chunkSize

		if end > len(runes) {
			end = len(runes)
		}

		chunks = append(chunks, string(runes[i:end]))
	}

	return chunks
}

func StructToString(v any) string {
	dataByte, err := json.Marshal(v)
	if err != nil {
		return ""
	}
	return string(dataByte)
}

func Md5File(filePath string) string {
	file, err := os.Open(filePath)
	if err != nil {
		return ""
	}
	defer file.Close()
	hash := md5.New()
	if _, err := io.Copy(hash, file); err != nil {
		return ""
	}
	md5Hash := hash.Sum(nil)
	return hex.EncodeToString(md5Hash)
}

func GetImageWH(filePath string) (width, height int) {
	file, err := os.Open(filePath)
	if err != nil {
		return
	}
	defer file.Close()
	img, _, err := image.Decode(file)
	if err != nil {
		fmt.Println(err)
		return
	}
	b := img.Bounds()
	width = b.Max.X
	height = b.Max.Y
	return
}

func MaxInt(a int, b int) int {
	if a > b {
		return a
	} else {
		return b
	}
}

// Base64Encode wrapper of base64.StdEncoding.EncodeToString
func Base64Encode(value []byte) string {
	return base64.StdEncoding.EncodeToString(value)
}

// Base64Decode wrapper of base64.StdEncoding.DecodeString
func Base64Decode(value string) ([]byte, error) {
	return base64.StdEncoding.DecodeString(value)
}

func CreateQrcode(url string) []byte {
	var png []byte
	png, err := goQrcode.Encode(url, goQrcode.Medium, 256)
	if err != nil {
	}
	return png
}
